package com.test.vote.controller;

import com.test.vote.pojo.Player;
import com.test.vote.response.CodeMsg;
import com.test.vote.response.ResultData;
import com.test.vote.service.playerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class photoController {

    @Autowired
    playerService playerService;

    //比赛管理员录入选手信息
    @PostMapping("/addPlayer")
    @ResponseBody
    public ResultData addPlayer(@RequestParam(value = "playerImg") MultipartFile file, @RequestParam(value = "playerName") String playerName, @RequestParam(value = "matchId") String matchId, @RequestParam(value = "playerNumber") String playerNumber, Model model) {
        //判断图片文件是否为空
        if (file.isEmpty()) {
            System.out.println("文件为空");
            return ResultData.error(CodeMsg.SERVER_ERROR);
        }
        String fileName = file.getOriginalFilename();  //文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  //后缀名
        String filePath = "D://vote//src//main//resources//static//img//"; //上传后的路径
        fileName = UUID.randomUUID() + suffixName; //新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filename = "/img/" + fileName;
        model.addAttribute("filename", filename);

        Player player = new Player();
        player.setPlayerImg(filename);
        player.setPlayerName(playerName);
        player.setPlayerNumber(playerNumber);
        player.setMatchId(Integer.valueOf(matchId));
        playerService.addPlayer(player);

        return ResultData.success(filename);
    }
}